import WebSocket from 'ws';
import fs from 'fs';
import path from 'path';

function getArg(name, def) {
  const idx = process.argv.indexOf(`--${name}`);
  if (idx !== -1 && idx + 1 < process.argv.length) return process.argv[idx + 1];
  return def;
}

const host = getArg('host', '127.0.0.1');
const port = Number(getArg('port', '4000'));
const chunks = Number(getArg('chunks', '500'));
const size = Number(getArg('size', '1024'));
const intervalMs = Number(getArg('interval', '10'));
const filePath = getArg('file', '');

const url = `ws://${host}:${port}`;
const ws = new WebSocket(url);

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function sendGenerated() {
  for (let i = 1; i <= chunks; i += 1) {
    const buf = Buffer.alloc(size, 0);
    ws.send(buf, { binary: true });
    if (i % 50 === 0) console.log(`已发送块: ${i}/${chunks}`);
    if (intervalMs > 0) await wait(intervalMs);
  }
}

async function sendFromFile() {
  const abs = path.isAbsolute(filePath) ? filePath : path.join(process.cwd(), filePath);
  const data = await fs.promises.readFile(abs);
  let sent = 0;
  for (let offset = 0; offset < data.length; offset += size) {
    const end = Math.min(offset + size, data.length);
    const slice = data.subarray(offset, end);
    ws.send(slice, { binary: true });
    sent += 1;
    if (sent % 50 === 0) console.log(`已发送块: ${sent} (offset=${end}/${data.length})`);
    if (intervalMs > 0) await wait(intervalMs);
  }
}

ws.on('open', async () => {
  console.log(`已连接: ${url}`);
  try {
    if (filePath) {
      await sendFromFile();
    } else {
      await sendGenerated();
    }
    console.log('发送完成，准备关闭连接');
    ws.close();
  } catch (err) {
    console.error('发送过程中出错:', err?.message || err);
    ws.close();
  }
});

ws.on('error', (err) => {
  console.error('客户端错误:', err?.message || err);
});

ws.on('close', (code, reason) => {
  const reasonText = Buffer.isBuffer(reason) ? reason.toString() : String(reason || '');
  console.log('连接已关闭:', code, reasonText);
});


